//
//  RHSystemInfoVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/2.
//

#import "RHSystemInfoVC.h"
#import "RHMeSystemModel.h"
#import "RHSystemInfoModel.h"
#import "RHSystemInfoCell.h"
#import "RHSystemInfoDeviceCell.h"
#import "RHDeviceModel.h"
#import "RHChoiceMultipleDeviceVC.h"

@interface RHSystemInfoVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@end

@implementation RHSystemInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"系统信息".rh_localized;
    [self createData];
    [self setupUI];
    [self getSystemInfo];
}

- (void)setupUI{
    QMUIButton *editBtn = [[QMUIButton alloc] init];
    [editBtn setTitle:@"修改".rh_localized forState:UIControlStateNormal];
    editBtn.titleLabel.font = kSYSTEMFONT(14);
    [editBtn setTitleColor:CMainColorGreen forState:UIControlStateNormal];
    [editBtn setBackgroundColor:UIColor.clearColor];
    [editBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [editBtn addTarget:self action:@selector(modifyAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn1 = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    
    self.navigationItem.rightBarButtonItem = rightBarBtn1;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
    [_tableView registerClass:[RHSystemInfoCell class] forCellReuseIdentifier:@"RHSystemInfoCell"];
    [_tableView registerClass:[RHSystemInfoDeviceCell class] forCellReuseIdentifier:@"RHSystemInfoDeviceCell"];
    [self.view addSubview:_tableView];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    

}

-(void)modifyAction:(QMUIButton*)btn
{
    if ([btn.titleLabel.text isEqualToString:@"修改".rh_localized]) {
        [btn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
        for (RHSystemInfoModel *model in self.dataArr) {
            model.isEdit = YES;
        }
        [self.tableView reloadData];
        [btn.titleLabel sizeToFit];
        btn.width = btn.titleLabel.width+1;
        return;
    }
    
    if ([btn.titleLabel.text isEqualToString:@"确认".rh_localized]) {
//        for (RHSystemInfoModel *model in self.dataArr) {
//            model.isEdit = NO;
//        }
//        [self.tableView reloadData];
        [self editSystemInfo];
    }
    
}

-(void)getSystemInfo
{
    [QMUITips showLoadingInView:kAppWindow];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_getSystemInfo,self.systemModel.systemId];
    [RHSystemInfoModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [self.dataArr enumerateObjectsUsingBlock:^(RHSystemInfoModel*  _Nonnull infoModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [infoModel readInfo:request.responseJSONObject[@"data"]];
            }];
            [self.tableView reloadData];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 0)];
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    kWeakSelf;
    RHSystemInfoModel *model = self.dataArr[indexPath.row];
    if ([model.tag isEqualToString:@"system_devices"]) {
        RHSystemInfoDeviceCell *deviceCell = [tableView dequeueReusableCellWithIdentifier:@"RHSystemInfoDeviceCell"];
     
        deviceCell.selectBlock = ^{
            [weakSelf getDeviceList:model];
        };
        deviceCell.deleteBlock = ^(NSInteger index){
            [weakSelf deleteDeviceFromSystem:model deviceIndex:index];
        };
        [deviceCell setModel:model];
        
        return deviceCell;
    }
    
    RHSystemInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHSystemInfoCell"];
 
    [cell setModel:model];
    [cell setCornerBorderWithIsFirstCell:indexPath.row == 0];
    cell.clickBlock = ^{
       
    };
    
    return cell;
}

#pragma mark ------ 删除设备
-(void)deleteDeviceFromSystem:(RHSystemInfoModel*)infoModel  deviceIndex:(NSInteger)index
{
    
    NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:infoModel.deviceList];
    [mtbArr removeObjectAtIndex:index];
    infoModel.deviceList = mtbArr.copy;
    [self.tableView reloadData];
    
//
//    [QMUITips showLoadingInView:kAppWindow];
//    NSString *deviceId = [infoModel.deviceList safeObjectAtIndex:index];
//    NSDictionary *para = @{
//        @"id":@(self.systemModel.systemId),
//        @"deviceList":@[deviceId]
//    };
//    __block NSArray *deviceLsit = infoModel.deviceList;
//    [BaseModel startWithCompletionAPIKey:H_systemDeleteDevice argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        if (resultModel.code == 200) {
//            NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:deviceLsit];
//            [mtbArr removeObjectAtIndex:index];
//            infoModel.deviceList = mtbArr.copy;
//            [self.tableView reloadData];
//            //通知系统列表更新
//            [kNotificationCenter postNotificationName:AssetSystemListNeedUpdateNotification object:nil];
//        }
//        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//            
//        }];
}

#pragma mark ---- 编辑系统信息
-(void)editSystemInfo
{
    [self.view endEditing:YES];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@(self.systemModel.systemId) forKey:@"id"];
    [self.dataArr enumerateObjectsUsingBlock:^(RHSystemInfoModel*  _Nonnull infoModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if (infoModel.canEdit) {
            if ([infoModel.tag isEqualToString:@"system_devices"]) {
                if (infoModel.deviceList.count>0) {
                    [para setObject:infoModel.deviceList forKey:@"deviceList"];//提交的字段跟获取的不一样
                }
            }else{
                if (infoModel.content>0) {
                    [para setObject:infoModel.content forKey:infoModel.key];
                }
            }
        }
    }];
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startPutWithCompletionAPIKey:H_systemEdit argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [kNotificationCenter postNotificationName:AssetSystemListNeedUpdateNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}

#pragma mark ----- 可添加的设备
-(void)getDeviceList:(RHSystemInfoModel*)model
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@([PrivateMange share].currentUser.userId),
                           @"pageNum":@(1),
                           @"pageSize":@(10000),
                           @"status":@""
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_getSystemDeviceListCanAdd argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            [self showDeviceList:arr model:model];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           [self.tableView endHeaderRefresh];
           [self.tableView endFooterRefresh];
    }];

}
-(void)showDeviceList:(NSArray*)deviceList  model:(RHSystemInfoModel*)model
{
    RHChoiceMultipleDeviceVC *vc = [[RHChoiceMultipleDeviceVC alloc]init];
    vc.deviceList = deviceList;
    vc.curDevices = model.deviceList;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    [vc showAnimation];
    kWeakSelf;
    vc.choiceResultBlock = ^(NSArray<NSString*> *arr) {
        model.deviceList = arr;
        model.content = [arr componentsJoinedByString:@","];
        [weakSelf.tableView reloadData];
    };
}



-(void)createData
{
    NSArray *datas = @[
        @{@"title":@"系统名称".rh_localized,
          @"placeHolder":@"请输入系统名称".rh_localized,
          @"canEdit":@(1),
          @"tag":@"system_name",
          @"key":@"name"
        },
        @{@"title":@"系统编号".rh_localized,
          @"key":@"systemNumber"
        },
        @{@"title":@"设备类型".rh_localized,
          @"placeHolder":@"请选择设备类型".rh_localized,
          @"isSelection":@(1),
          @"tag":@"device_type",
          @"key":@"systemType"
        },
        @{@"title":@"设备数量".rh_localized,
          @"key":@"deviceNumber"
        },
        @{@"title":@"装机容量".rh_localized,
          @"unit":@"kWh",
          @"key":@"installedCapacity"
        },
        @{@"title":@"装机功率".rh_localized,
          @"unit":@"kW",
          @"key":@"installedPower"
        },
        @{@"title":@"系统状态".rh_localized,
          @"key":@"status",
          @"isSelection":@(1),
          @"optionList":@[
              @{
                  @"typeId":@(0),
                  @"typeName":@"正常"
              },
              @{
                  @"typeId":@(1),
                  @"typeName":@"告警"
              },
              @{
                  @"typeId":@(2),
                  @"typeName":@"故障"
              },
              @{
                  @"typeId":@(3),
                  @"typeName":@"保护"
              }
          ],
        },
//        @{@"title":@"投建日期".rh_localized,
//          @"key":@"createTime"
//        },
        @{@"title":@"联系人".rh_localized,
          @"placeHolder":@"输入联系人".rh_localized,
          @"canEdit":@(1),
          @"tag":@"system_contact",
          @"key":@"contact"
        },
        @{@"title":@"联系电话".rh_localized,
          @"placeHolder":@"请输入联系人电话".rh_localized,
          @"canEdit":@(1),
          @"tag":@"system_contact_phone",
          @"key":@"contactNumber"
        },
        @{@"title":@"所属电站".rh_localized,
          @"key":@"plantName"
        },
        @{@"title":@"所属上级组织".rh_localized,
          @"key":@"orgName"
        },
        @{@"title":@"下级设备".rh_localized,
          @"placeHolder":@"添加设备".rh_localized,
          @"canEdit":@(1),
          @"isSelection":@(1),
          @"tag":@"system_devices",
          @"key":@"deviceInfoList"
        },
    ];
    
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHSystemInfoModel class] json:datas];
}


@end
